﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace Core.Framework.Util.Attributes
{
    public static partial class Attributes
    {
        /// <summary>
        /// 数据验证
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static Tuple<bool, string> IsValid<T>(this T model, IsValidEnum e = IsValidEnum.init) where T : class
        {
            Type type = model.GetType();

            // 验证字段
            foreach (var field in type.GetFields())
            {
                if (field.IsDefined(typeof(ValidationAttribute), true))
                {
                    var attrs = Attribute.GetCustomAttributes(field, typeof(ValidationAttribute), true);
                    foreach (ValidationAttribute attr in attrs)
                        if (!attr.IsValid(field.GetValue(model)))
                            return new Tuple<bool, string>(false, attr.ErrorMessage);
                }
            }

            // 验证属性
            foreach (var property in type.GetProperties())
            {
                if (property.IsDefined(typeof(ValidationAttribute), true))
                {
                    var attrs = Attribute.GetCustomAttributes(property, typeof(ValidationAttribute), true);
                    foreach (ValidationAttribute attr in attrs)
                        if (!attr.IsValid(property.GetValue(model)))
                            return new Tuple<bool, string>(false, attr.ErrorMessage);
                }
            }

            return new Tuple<bool, string>(true, "");
        }

        public enum IsValidEnum
        {
            /// <summary>
            /// 默认
            /// </summary>
            init,
            /// <summary>
            /// 注册
            /// </summary>
            reg,
            /// <summary>
            /// 修改
            /// </summary>
            update,
            /// <summary>
            /// 删除
            /// </summary>
            delete,
            /// <summary>
            /// 查询时
            /// </summary>
            select
        }

    }
}
